/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.web.servlet.handler.bluemartini;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.martinimix.dao.environment.EnvironmentDao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bluemartini.dna.BMThreadManager;

/**
 * Provides a request handler to set Blue Martini's thread
 * manager state for an environment.
 * 
 * This class and its derivatives are only necessary in a Blue Martini
 * environment.
 * 
 * @author Scott Rossillo
 *
 */
public abstract class AbstractBlueMartiniTheadManagerHandler extends HandlerInterceptorAdapter {
	
	/**
	 * The log for this handler and its subclasses.
	 */
	protected final static Log log = LogFactory.getLog(AbstractBlueMartiniTheadManagerHandler.class);
	
	/**
	 * The environment data access object for this handler.
	 */
	private EnvironmentDao environmentDao;
	
	/**
	 * Creates a new Blue Martini thread manager handler.
	 */
	protected AbstractBlueMartiniTheadManagerHandler() { }

	/**
	 * Sets the appropriate Blue Martini version, if necessary.
	 */
	public final boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		setThreadVersion();
		if(BMThreadManager.getUserAccountID() == null) {
			BMThreadManager.setUserAccountID(environmentDao.getDefaultUserId());
		}
		
		return true;
	}
	
	/**
	 * Sets the current version for the current request's thread.
	 * 
	 * @throws ServletException if the thread version cannot be set
	 */
	protected abstract void setThreadVersion() throws ServletException;
	
	
	/**
	 * Returns the environment data access object associated with this
	 * handler.
	 * 
	 * @return the <code>EnvironmentDao</code> associated with this handler
	 * or <code>null</code> if none has been assigned
	 */
	public EnvironmentDao getEnvironmentDao() {
		return environmentDao;
	}

	/**
	 * Sets the environment data access object for this handler.
	 * 
	 * @param environmentDao the <code>EnvironmentDao</code> for this handler
	 */
	public void setEnvironmentDao(EnvironmentDao environmentDao) {
		this.environmentDao = environmentDao;
	}
}
